package com.bw.lib_base.mvvm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.SPUtils
import com.bw.lib_base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.Exception
import java.lang.RuntimeException
import java.text.SimpleDateFormat

open class BaseViewModel:ViewModel() {
    val onFailed by lazy { MutableLiveData<Throwable>() }

    fun <T> httpRequest(s:suspend ()-> Res<T>,
                    success:(T)->Unit,
                    failed:(Throwable)->Unit=onFailed::postValue){
        viewModelScope.launch {
            try {
                val res = s.invoke()//调用apiService里的接口
                if(res.code==200){
                    Log.i("===",res.toString())
                    success(res.data)
                }else{
                    Log.d("----code", res.msg+",code:"+res.code)
                    failed(RuntimeException(res.msg))
                }
            }catch (e:Exception){
                Log.d("----error", e.message.toString())
                failed(e)
            }
        }
    }

}